package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.jzo2o.api.publics.SmsCodeApi;
import com.jzo2o.api.publics.dto.response.BooleanResDTO;
import com.jzo2o.common.constants.UserType;
import com.jzo2o.common.enums.SmsBussinessTypeEnum;
import com.jzo2o.customer.model.domain.CommonUser;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.InstitutionRegisterReqDTO;
import com.jzo2o.customer.service.ICommonUserService;
import com.jzo2o.customer.service.IServeProviderService;
import com.jzo2o.customer.service.RegisterService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author itlxc
 * @since 2024-10-13
 */
@Service
@RequiredArgsConstructor
public class RegisterServiceImpl implements RegisterService {


    private final IServeProviderService serveProviderService;

    private final PasswordEncoder passwordEncoder;

    @Resource
    private SmsCodeApi smsCodeApi;

    /**
     * 机构人员注册
     * @param dto
     */
    @Override
    public void register(InstitutionRegisterReqDTO dto) {

        // 1.判断验证码是否正确
        BooleanResDTO verify = smsCodeApi.verify(dto.getPhone(), SmsBussinessTypeEnum.INSTITION_REGISTER, dto.getVerifyCode());
        if (!verify.getIsSuccess()) {
            throw new RuntimeException("验证码错误，请重新输入");
        }
        // 2.判断手机号是否已注册
        ServeProvider serveProvider = serveProviderService.lambdaQuery()
                .eq(ServeProvider::getPhone, dto.getPhone())
                .one();
        if (ObjectUtil.isNotNull(serveProvider)) {
            throw new RuntimeException("该手机号已注册");
        }
        // 3.注册账号
        serveProvider = new ServeProvider();
        serveProvider.setPhone(dto.getPhone());
        serveProvider.setPassword(passwordEncoder.encode(dto.getPassword()));
        serveProvider.setType(UserType.INSTITUTION);
        serveProvider.setStatus(0);
        boolean flag = serveProviderService.save(serveProvider);
        if (!flag) {
            throw new RuntimeException("注册失败");
        }
    }
}
